<template>
  <div class="address">
    <van-form ref="form">
      <van-field
        v-model="formData.receiver"
        clearable
        required
        name="姓名"
        label="姓名"
        placeholder="收货人姓名"
        :error="false"
        :rules="rules.receiver"
      />
      <van-field
        v-model="formData.receiverContact"
        clearable
        required
        name="电话"
        label="电话"
        placeholder="收货人手机号"
        :rules="rules.tel"
      />
      <van-field
        v-model="areaValue"
        required
        is-link
        name="地区"
        label="地区"
        placeholder="点击选择省/市/区"
        :rules="rules.areaValue"
        @click="showArea = true"
      />
      <van-popup v-model="showArea" round position="bottom">
        <van-cascader
          v-model="cascaderValue"
          title="请选择所在地区"
          :options="dataList"
          @change="loadData"
          @close="showArea = false"
          @finish="onFinish"
        />
      </van-popup>

      <van-field
        v-model="formData.detailAddr"
        clearable
        required
        name="详细地址"
        label="详细地址"
        placeholder="请填写详细地址"
        :rules="rules.detailAddr"
      />
    </van-form>

    <van-cell class="defBox" title="设为默认收货地址">
      <template #right-icon>
        <van-switch style="font-size: 24px" v-model="formData.isDefault" />
      </template>
    </van-cell>
    <van-notice-bar color="#1989fa" background="#ecf9ff" left-icon="info-o">
      已保存 {{ listNum }} 了条地址，还能保存 {{ surplus }} 条地址
    </van-notice-bar>
    <div class="btnBox">
      <van-button round type="info" block @click="onSubmit">保存</van-button>
      <van-button v-if="isEdit" round block @click="onDelete">删除</van-button>
    </div>
    <fullLoading v-if="loading"></fullLoading>
  </div>
</template>

<script>
import { queryArea } from "@/api/common";
import {
  addAddress,
  editAddress,
  delAddress,
} from "@api/platframe/mainFrame/address";

export default {
  data() {
    return {
      isEdit: false,
      loading: false,
      areaValue: "", //所选地区
      cascaderValue: "",
      listNum: 0, // 有多少数据
      surplus: 10, // 还能生成多少条
      showArea: false, // 地区弹窗显示
      dataList: [], //
      // 收货人信息初始值
      formData: {
        addrId: "", // 收货地址标识
        cityCode: "", // 市编码
        cityName: "", // 市名称
        countyCode: "", // 县编码
        countyName: "", // 县名称
        detailAddr: "", // 详细地址
        isDefault: false, // 是否默认 1：是 0：否
        provCode: "", // 省编码
        provName: "", // 省名称
        receiver: "", // 收货人
        receiverContact: "", // 收货人手机号
        staffId: "", // 人员标识
      },
      // 必填项校验
      rules: {
        receiver: [
          { required: true, message: "请填写收货人姓名", trigger: "onBlur" },
        ],
        tel: [
          { required: true, message: "请填写收货人手机号", trigger: "onBlur" },
          {
            pattern: this.$commonReg.phoneReg,
            message: this.$commonReg.phoneMsg,
            trigger: "onBlur",
          },
        ],
        areaValue: [{ required: true, message: "请选择地区", trigger: "blur" }],
        detailAddr: [
          { required: true, message: "请填写详细地址", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getInitTree();
  },
  methods: {
    // 获取地址树
    getInitTree() {
      queryArea("", "1").then((res) => {
        if (res.code == "1000") {
          let data = res.data;
          data = this.operationTree(data);
          this.dataList = data;
        }
      });
    },
    // 切换地区
    loadData(item) {
      item.loading = true;
      queryArea(item.value, Number(item.tabIndex) + 2).then((res) => {
        item.loading = false;
        if (res.code == "1000") {
          let data = res.data;
          data = this.operationTree(data);
          if (item.tabIndex == 0) {
            item.selectedOptions[0].children = data;
          } else {
            item.selectedOptions[1].children = data;
          }
        }
      });
    },
    // 处理地址树
    operationTree(arr) {
      let arrData = [];
      arr.forEach((item) => {
        if (item.areaLevel > 2) {
          arrData.push({
            value: item.areaCode,
            text: item.areaName,
          });
        } else {
          arrData.push({
            value: item.areaCode,
            text: item.areaName,
            level: item.areaLevel,
            children: [],
            // loading: false,
          });
        }
      });
      return arrData;
    },
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish(item) {
      this.showArea = false;
      this.areaValue = item.selectedOptions
        .map((option) => option.text)
        .join("/");
      this.formData.provCode = item.selectedOptions[0].value;
      this.formData.cityCode = item.selectedOptions[1].value;
      this.formData.countyCode = item.selectedOptions[2].value;
    },

    // 查询原本信息
    getData(obj) {
      this.isEdit = true;
      for (var key in this.formData) {
        if (obj[key] || obj[key] === 0) {
          this.formData[key] = obj[key];
        }
      }
      this.formData.isDefault = obj.isDefault == "1" ? true : false;
      this.areaValue = obj.provName + "/" + obj.cityName + "/" + obj.countyName;
    },

    // 保存
    onSubmit() {
      // 全局表单验证
      this.$refs.form
        .validate()
        .then(() => {
          let arr = this.areaValue.split("/");
          this.formData.provName = arr[0];
          this.formData.cityName = arr[1];
          this.formData.countyName = arr[2];
          if (this.formData.isDefault) {
            this.formData.isDefault = "1";
          } else {
            this.formData.isDefault = "0";
          }

          this.Interface();
        })
        .catch(() => {
          // this.$toast.fail('请完成必填项！')
        });
    },
    // 走接口(新增/修改)
    async Interface() {
      let obj = { ...this.formData };
      let userid = sessionStorage.getItem("userid");
      obj.staffId = userid;
      let res = null;
      if (!this.isEdit) {
        res = await addAddress(obj);
      } else {
        res = await editAddress(obj);
      }

      if (res && res.code === 1000) {
        this.$Notify({ type: "success", message: "保存成功！" });
        this.$emit("close");
        this.$emit("refresh");
      }
    },
    // 删除
    async onDelete() {
      let obj = {
        addrIdList: this.formData.addrId,
      };
      let res = await delAddress(obj);
      if (res && res.code === 1000) {
        this.$Notify({ type: "success", message: "删除成功！" });
        this.$emit("close");
        this.$emit("refresh");
      }
    },
    // 重置表单
    resetForm() {
      this.formData = {
        addrId: "", // 收货地址标识
        cityCode: "", // 市编码
        cityName: "", // 市名称
        countyCode: "", // 县编码
        countyName: "", // 县名称
        detailAddr: "", // 详细地址
        isDefault: false, // 是否默认 1：是 0：否
        provCode: "", // 省编码
        provName: "", // 省名称
        receiver: "", // 收货人
        receiverContact: "", // 收货人手机号
        staffId: "", // 人员标识
      };
      this.isEdit = false;
      this.showArea = false;
      this.loading = false;
      this.areaValue = "";
      this.cascaderValue = "";
      this.listNum = 0; // 有多少数据
      this.surplus = 10; // 还能生成多少条
      setTimeout(() => {
        this.$refs.form.resetValidation();
      });
    },
  },
};
</script>

<style scoped lang="less">
::v-deep .van-nav-bar__left {
  i,
  .van-nav-bar__text {
    color: #000;
  }
}
::v-deep .van-button--danger {
  background-color: #1989fa;
  border-color: #1989fa;
}
.address {
  padding: 12px;
  height: calc(100% - 25px);
  overflow: auto;
  background-color: #f4f7fa;
  .van-form {
    div:nth-child(1) {
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
    }
    div:nth-child(4) {
      border-bottom-right-radius: 10px;
      border-bottom-left-radius: 10px;
    }
  }
  .fieldsBox {
    overflow: hidden;
    border-radius: 10px;
  }
  .defBox {
    margin-top: 12px;
    overflow: hidden;
    border-radius: 8px;
  }
  .btnBox {
    padding: 22px 0px;
    .van-button {
      margin-bottom: 12px;
    }
  }
}
</style>
